package com.sinapsisempresarial.io;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class CneTestServlet extends HttpServlet {
    
	public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws IOException {	

	StringBuffer contenido = new StringBuffer();
		
    try {
    	
    	String nacionalidad = req.getParameter("nacionalidad");
    	String cedula = req.getParameter("cedula");
    	
        URL url = new URL("http://www.cne.gov.ve/web/registro_electoral/ce.php?nacionalidad=" + nacionalidad + "&cedula=" + cedula);
       
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String line;
        int i = 0;
        while ((line = reader.readLine()) != null) {
        	if(i==33)
        		contenido.append(line);
        	i++;
        }
        reader.close();

    } catch (MalformedURLException e) {

    } catch (IOException e) {

    }
    
    try{
        DocumentBuilderFactory domFactory = 
            DocumentBuilderFactory.newInstance();
                  domFactory.setNamespaceAware(true); 
            DocumentBuilder builder = domFactory.newDocumentBuilder();

            InputStream is = new ByteArrayInputStream(contenido.toString().getBytes("UTF-8"));	        
            
            Document doc = builder.parse(is);

            XPath xpath = XPathFactory.newInstance().newXPath();

            XPathExpression expr = xpath.compile("//td/strong/text()");

            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            
            ServletOutputStream salida = res.getOutputStream();

            res.setContentType("text/html");           
            
            for (int i = 0; i < nodes.getLength(); i++) {
            	salida.println(nodes.item(i).getNodeValue()); 
            }    

    }catch (Exception e) {
	}
        
    
    
	 }
}
